﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SmartSpace.UI.Silverlight;
using System.Windows.Threading;
using RTC.UI.ServiceRef;
using System.Windows.Browser;

namespace RTC.UI
{
    public partial class ChatView : AppView
    {
        private string _originalTitle;
        private int _messageScroll;
        private bool _newMessage;

        private int _refreshUser;
        private bool _isRefresh;
        private DispatcherTimer _timer;

        public ChatView()
            : base(new Guid("{8CBFCBAC-25B7-4794-AF4D-21182207EFDD}"), "chat view")
        {
            InitializeComponent();

            _originalTitle = HtmlPage.Document.GetProperty("title").ToString();
            this.MouseMove += new MouseEventHandler(ChatView_MouseMove);
        }

        void ChatView_MouseMove(object sender, MouseEventArgs e)
        {
            _newMessage = false;
            _messageScroll = 0;
            HtmlPage.Document.SetProperty("title", _originalTitle);
        }

        protected override void OnExtendShown()
        {
            base.OnExtendShown();

            RTCWebServiceSoapClient client = RTCModule.CreateRTCProxy();
            client.OnlineCompleted += new EventHandler<OnlineCompletedEventArgs>(client_OnlineCompleted);
            client.OnlineAsync(this.Authentication.Account);
        }

        protected override void OnHidden()
        {
            if (_timer != null)
            {
                _timer.Stop();
            }

            RTCWebServiceSoapClient client = RTCModule.CreateRTCProxy();
            client.OfflineCompleted += new EventHandler<OfflineCompletedEventArgs>(client_OfflineCompleted);
            client.OfflineAsync(this.Authentication.Account);

            
            base.OnHidden();
        }

        void client_OnlineCompleted(object sender, OnlineCompletedEventArgs e)
        {
            Paragraph paragraph = new Paragraph();
            Run run = new Run();
            run.Foreground = new SolidColorBrush(Colors.Red);
            run.Text = ">>连接成功!";
            paragraph.Inlines.Add(run);
            _ctlEditMessage.Blocks.Add(paragraph);
            _ctlScrollViewer.ScrollToVerticalOffset(double.MaxValue);

            if (_timer == null)
            {
                _timer = new DispatcherTimer();
                _timer.Interval = new TimeSpan(0, 0, 2);
                _timer.Tick += new EventHandler(_timer_Tick);
            }
            _timer.Start();
        }

        void client_OfflineCompleted(object sender, OfflineCompletedEventArgs e)
        {
        }

        #region 刷新
        void _timer_Tick(object sender, EventArgs e)
        {
            RTCWebServiceSoapClient client = RTCModule.CreateRTCProxy();
            client.GetMessageCompleted += new EventHandler<GetMessageCompletedEventArgs>(client_GetMessageCompleted);
            client.GetMessageAsync(this.Authentication.Account);

            _refreshUser++;

            if (_refreshUser % 4 == 0)
            {
                client.GetOnlineUsersCompleted += new EventHandler<GetOnlineUsersCompletedEventArgs>(client_GetOnlineUsersCompleted);
                client.GetOnlineUsersAsync();
                _refreshUser = 0;
                _ctlLog.Text = string.Format("refreshing message and user{0}", DateTime.Now.Ticks);
            }
            else
            {
                _ctlLog.Text = string.Format("refreshing message{0}", DateTime.Now.Ticks);
            }

            if (_newMessage)
            {
                if (_messageScroll % 2 == 1)
                {
                    _messageScroll = 0;
                    HtmlPage.Document.SetProperty("title", "【★★★新消息★★★】请查看新消息!");
                }
                else
                {
                    _messageScroll++;
                    HtmlPage.Document.SetProperty("title", "〖☆☆☆新消息☆☆☆〗请查看新消息!");
                }
            }
        }

        void client_GetOnlineUsersCompleted(object sender, GetOnlineUsersCompletedEventArgs e)
        {
            if (e.Error == null && e.Result.IsSuccess)
            {
                _ctlListUser.ItemsSource = e.Result.Data;
            }
        }
        #endregion

        void client_GetMessageCompleted(object sender, GetMessageCompletedEventArgs e)
        {
            if (e.Error == null && e.Result.IsSuccess)
            {
                if (e.Result.Data.Count > 0)
                {
                    _newMessage = true;
                }

                foreach (var item in e.Result.Data)
                {
                    Paragraph paragraph = new Paragraph();

                    Run accountEl = new Run();
                    accountEl.Text = item.Account;
                    accountEl.Foreground = new SolidColorBrush(Colors.Blue);
                    accountEl.FontWeight = FontWeights.Bold;
                    paragraph.Inlines.Add(accountEl);

                    Run timespanEl = new Run();
                    timespanEl.Text = " " + item.Timestamp.ToString("hh:mm:ss");
                    timespanEl.Foreground = new SolidColorBrush(Colors.Blue);
                    timespanEl.FontWeight = FontWeights.Bold;
                    paragraph.Inlines.Add(timespanEl);

                    LineBreak lineEl = new LineBreak();
                    paragraph.Inlines.Add(lineEl);

                    Run contentEl = new Run();
                    contentEl.Text = "    " + item.Content;
                    paragraph.Inlines.Add(contentEl);
                    _ctlEditMessage.Blocks.Add(paragraph);
                }
            }
        }

        private void _ctlBtnSend_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_ctlEditInput.Text.Trim()))
            {
                MessageBox.Show("输入内容!");
                return;
            }
            string message = _ctlEditInput.Text.Trim();


            RTCWebServiceSoapClient client = RTCModule.CreateRTCProxy();
            client.SendMessageCompleted += new EventHandler<SendMessageCompletedEventArgs>(client_SendMessageCompleted);
            client.SendMessageAsync(this.Authentication.Account, message);

            _ctlEditInput.Text = string.Empty;
        }

        void client_SendMessageCompleted(object sender, SendMessageCompletedEventArgs e)
        {
            if (e.Error == null && e.Result.IsSuccess)
            {
            }
            else
            {
                MessageBox.Show("发送失败!");
            }
        }

        private void _ctlEditMessage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _ctlScrollViewer.ScrollToVerticalOffset(_ctlScrollViewer.ScrollableHeight);
        }
    }
}
